<script setup lang="ts">
import { onMounted, ref } from "vue";
import { search, findAllVideo } from "@/api/video/search";
import { VideoVo } from "@/types/VideoVo"; // 引入 VideoVo 接口
import bilibilicon from "@/assets/bilibiliavatar.png";
import router from "@/router";

// 创建一个响应式变量来存储视频数据
const videosList = ref<VideoVo[]>([]);
const videos = ref<VideoVo[]>([]);

const infiniteId = 1;
const currentPage = ref(0);
const total = ref(0);

const recommendThumbnail = bilibilicon;

const leftChannels = [
  {
    name: "番剧",
    id: "anime",
    href: "https://www.bilibili.com/anime/",
  },
  {
    name: "国创",
    id: "guochuang",
    href: "https://www.bilibili.com/anime/",
  },
  {
    name: "综艺",
    id: "variety",
    href: "https://www.bilibili.com/anime/",
  },
  {
    name: "动画",
    id: "douga",
    href: "https://www.bilibili.com/anime/",
  },
  {
    name: "鬼畜",
    id: "kichiku",
    href: "https://www.bilibili.com/anime/",
  },
  {
    name: "舞蹈",
    id: "dance",
    href: "https://www.bilibili.com/anime/",
  },
  {
    name: "娱乐",
    id: "ent",
    href: "https://www.bilibili.com/anime/",
  },
  {
    name: "科技",
    id: "tech",
    href: "https://www.bilibili.com/anime/",
  },
  {
    name: "美食",
    id: "food",
    href: "https://www.bilibili.com/anime/",
  },
  {
    name: "汽车",
    id: "car",
    href: "https://www.bilibili.com/anime/",
  },
  {
    name: "运动",
    id: "sports",
    href: "https://www.bilibili.com/anime/",
  },
  {
    name: "电影",
    href: "https://www.bilibili.com/anime/",
  },
  {
    name: "电视剧",
    href: "https://www.bilibili.com/anime/",
  },
  {
    name: "纪录片",
    href: "https://www.bilibili.com/anime/",
  },
  {
    name: "游戏",
    href: "https://www.bilibili.com/anime/",
  },
  {
    name: "音乐",
    href: "https://www.bilibili.com/anime/",
  },
  {
    name: "影视",
    href: "https://www.bilibili.com/anime/",
  },
  {
    name: "知识",
    href: "https://www.bilibili.com/anime/",
  },
  {
    name: "资讯",
    href: "https://www.bilibili.com/anime/",
  },
  {
    name: "生活",
    href: "https://www.bilibili.com/anime/",
  },
  {
    name: "时尚",
    href: "https://www.bilibili.com/anime/",
  },
  {
    name: "其他",
    href: "https://www.bilibili.com/anime/",
  },
];
const rightChannels = [
  {
    name: "专栏",
    href: "https://www.bilibili.com/anime/",
  },
  {
    name: "活动",
    href: "https://www.bilibili.com/anime/",
  },
  {
    name: "课堂",
    href: "https://www.bilibili.com/anime/",
  },
  {
    name: "直播",
    href: "https://www.bilibili.com/anime/",
  },
  {
    name: "社区中心",
    href: "https://www.bilibili.com/anime/",
  },
  {
    name: "新歌热榜",
    href: "https://www.bilibili.com/anime/",
  },
];
const image = [
  "https://msp-1.oss-cn-beijing.aliyuncs.com/20240821/img/cover/1724245288062b5a9c3c2134e4a29aa121d47b6ed0c6f.jpg",
  "https://msp-1.oss-cn-beijing.aliyuncs.com/20240821/img/cover/1724245288062b5a9c3c2134e4a29aa121d47b6ed0c6f.jpg",
  "https://msp-1.oss-cn-beijing.aliyuncs.com/20240821/img/cover/1724247126880b6f1faf9a2d640309b2cb16f379a1365.jpg",
];
async function fetchVideos() {
  try {
    const response = await search(); // 调用后端 API
    // 假设 search 函数返回的是一个包含 VideoVo 对象的数组
    if (Array.isArray(response)) {
      videosList.value = response as VideoVo[];
    } else {
      console.error("Expected an array of VideoVo, but got:", response);
    }
  } catch (error) {
    console.error("Failed to fetch videos:", error);
  }
}
const jumpToVideoDetail = (video) => {
  console.log(video.vid,video.uid);
  router
    .push({
      path: "/newVideoDetail",
      query: {
        vid: video.vid,
        uid: video.uid,
      },
    })
    .then(() => {
      // 确保路由跳转完成后再刷新页面
      window.location.reload();
    });
};

const pageListVideos = ($state) => {
  let pageNum = currentPage.value + 1; // 使用 .value 访问响应式引用的值
  let pageSize = 10;
  findAllVideo(pageNum, pageSize)
    .then((response) => {
      const { list: newVideos, total: totalCount } = response; // 重命名以避免混淆
      if (newVideos.length === 0) {
        $state.complete();
        return;
      }

      // 使用扩展运算符合并数组
      videos.value = [...videos.value, ...newVideos];

      // 更新总视频数
      total.value = totalCount;

      // 递增当前页码
      currentPage.value++;

      // 标记加载完成
      $state.loaded();
    })
    .catch((error) => {
      console.error("请求出错:", error);
      $state.complete();
    });
};
const formatCreateDate = (dateString) => {
  if (dateString == null) {
    return "-";
  }
  // 使用正则表达式匹配年、月、日、时、分、秒
  const match = dateString.match(
    /(\w{3}) (\w{3}) (\d{2}) (\d{2}):(\d{2}):(\d{2}) (\w{3}) (\d{4})/
  );
  if (!match) {
    // 如果没有匹配到，返回占位符
    return "-";
  }
  // 提取月、日和年（虽然在这个例子中我们不需要年）
  const month = match[2];
  const day = match[3];
  // 注意：这里我们没有直接使用年、月、日来创建一个新的Date对象
  // 因为我们只需要月和日的字符串表示
  // 但如果你需要一个Date对象，你可以这样做：
  // const date = new Date(match[8], monthsIndex[match[2].toLowerCase()], parseInt(match[3], 10));
  // 其中monthsIndex是一个包含月份索引的对象或数组（因为月份在Date构造函数中是0-11）

  // 直接返回月-日的字符串
  return `${month.slice(0, 3)}-${day.padStart(2, "0")}`; // 假设月份缩写总是3个字符长
};
const ToString = (video) => {
  console.log(video);
};

const ToPath = (name) => {
  if (name == "") {
    window.alert("错误选择!");
    return;
  }
  //判断是否重复跳转
  // 判断是否重复跳转，如果是，则刷新页面
  if (
    decodeURIComponent(router.currentRoute.value.fullPath) ===
    `/videosearch?searchCategory=${encodeURIComponent(name)}`
  ) {
    location.reload();
    return;
  }
  router
    .push({
      path: "/videosearch",
      query: {
        searchCategory: name,
      },
    })
    .then(() => {
      // 确保路由跳转完成后再刷新页面
      window.location.reload();
    });
};

onMounted(() => {
  fetchVideos();
});
</script>

<template>
  <div class="main-page">
    <!--分区导航-->
    <div class="main-page-channel-container">
      <div class="left-channel">
        <div class="left-channel-recommend">
          <img :src="recommendThumbnail" alt="" />
          <span>推荐</span>
        </div>
        <div class="left-channel-recommend">
          <img :src="recommendThumbnail" alt="" />
          <span>热门</span>
        </div>
      </div>

      <div class="right-channel">
        <div class="right-channel-left">
          <a
            class="right-channel-left-link"
            v-for="(channel, index) in leftChannels"
            :key="index"
            @click="ToPath(channel.name)"
            target="_blank"
          >
            {{ channel.name }}
          </a>
        </div>
        <div class="right-channel-right">
          <a
            class="right-channel-right-link"
            v-for="(channel, index) in rightChannels"
            :key="index"
            :href="channel.href"
            target="_blank"
          >
            {{ channel.name }}
          </a>
        </div>
      </div>
    </div>
    <el-button @click="fetchVideos()" class="rightbutton">刷新</el-button>
    <!--走马灯和视频块-->
    <div class="main-page-video-container">
      <div class="carousel-container">
        <el-carousel :interval="5000" arrow="always" class="carousel">
          <el-carousel-item v-for="(image, index) in image" :key="index">
            <img
              :src="image"
              alt="carousel image"
              style="width: 100%; height: 100%; border-radius: 5px"
            />
          </el-carousel-item>
        </el-carousel>
      </div>
      <div
        class="video-container"
        v-for="video in videosList"
        :key="video.vid"
        @click="jumpToVideoDetail(video)"
      >
        <img :src="video.coverUrl" class="thumbnail" alt="" />
        <span>{{ video.title }}</span>
        <div class="videos-details">
          <div class="video-count-item">
            <img src="@/assets/icons/viewCount.png" alt="" />
            {{ video.play ? video.play : "-" }}
          </div>
          <div class="danmu-count-item">
            <img src="@/assets/icons/danmuCount.png" alt="" />
            {{ video.comment ? video.comment : "-" }}
          </div>
          <div class="videos-time">
            {{ video.createDate }}
          </div>
        </div>
      </div>
      <div
        class="video-container"
        v-for="video2 in videos.values()"
        :key="video2.vid"
        @click="jumpToVideoDetail(video2)"
      >
        <img :src="video2.coverUrl" class="thumbnail" alt="" />
        <span>{{ video2.title }}</span>
        <div class="videos-details">
          <div class="video-count-item">
            <img src="@/assets/icons/viewCount.png" alt="" />
            {{ video2.play ? video2.play : "-" }}
          </div>
          <div class="danmu-count-item">
            <img src="@/assets/icons/danmuCount.png" alt="" />
            {{ video2.comment ? video2.comment : "-" }}
          </div>
          <div class="videos-time">
            {{ video2.createDate }}
          </div>
        </div>
      </div>
      <infinite-loading :infinite-id="infiniteId" @infinite="pageListVideos" />
    </div>
  </div>
</template>

<style scoped lang="less">
.main-page {
  background-color: white;
  .main-page-channel-container {
    display: flex;
    margin-top: 40px;
    align-items: center;
    justify-content: space-between;
    margin-left: 5%;
    margin-right: 5%;

    .left-channel {
      margin-top: 10px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-right: 20px;
      .left-channel-recommend {
        display: flex;
        align-items: center;
        flex-direction: column;
        img {
          height: 40px;
          width: 40px;
          border-radius: 50%;
        }
      }
    }

    .right-channel {
      margin-top: 10px;
      width: 100%;
      display: flex;
      justify-content: space-between;
      .right-channel-left {
        display: grid;
        grid-gap: 10px;
        grid-template-rows: repeat(2, 1fr);
        grid-auto-flow: column;
        border-right: 1px solid gray;
        padding-right: 30px;
        width: 100%;
        .right-channel-left-link {
          height: 26px;
          text-align: center;
          background-color: #f5f7f8;
          color: black;
          border-radius: 5px;
          width: 100%;
          cursor: pointer;
          text-decoration: none;
        }
      }

      .right-channel-right {
        width: 240px;
        display: grid;
        grid-auto-flow: column;
        grid-template-rows: repeat(2, 1fr);
        padding-left: 20px;

        .right-channel-right-link {
          color: black;
          text-decoration: none;
        }
      }
    }
  }

  .main-page-video-container {
    display: grid;
    grid-gap: 20px;
    grid-template-columns: repeat(5, 1fr);
    height: 100%;
    flex-shrink: 0;
    margin-right: 5%;
    margin-left: 5%;
    margin-top: 40px;

    .carousel-container {
      grid-column: 1/3;
      grid-row: 1/3;
      cursor: pointer;
      .carousel {
        height: 100%;
        max-height: 480px;
        ::v-deep .el-carousel__container {
          height: 100%;
          min-height: 400px;
        }
      }
    }

    .video-container {
      display: flex;
      flex-direction: column;
      font-size: 16px;
      height: 100%;
      cursor: pointer;
      justify-content: space-between;
      .thumbnail {
        width: 100%;
        max-width: 320px;
        height: 180px;
        border-radius: 5px;
      }
      .videos-details {
        display: flex;
        align-items: center;
        width: 100%;
        margin-top: 10px;
        margin-bottom: 10px;
        .video-count-item {
          display: flex;
          align-items: center;
          margin-right: 10px;
          img {
            max-height: 26px;
            max-width: 26px;
            margin-right: 5px;
          }
        }
        .danmu-count-item {
          display: flex;
          align-items: center;
          margin-right: 10px;
          img {
            max-height: 26px;
            max-width: 26px;
            margin-right: 5px;
          }
        }
        .videos-time {
          color: gray;
          font-size: 16px;
        }
      }
    }

    @media (max-width: 1680px) {
      grid-template-columns: repeat(4, 1fr);
    }

    @media (max-width: 768px) {
      grid-template-columns: repeat(2, 1fr);
    }
  }
}
.rightbutton {
  float: right; /* 或使用 flex 布局 */
  margin-right: 80px;
}
</style>
